﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ReferralTracker.Data.Contexts;
using ReferralTracker.BusinessObjects.Infrastructure;
using ReferralTracker.Data.Entities;
using ReferralTracker.Data.Lookups;
using ReferralTracker.Data.Repositories;

namespace ReferralTracker.BusinessObjects {
    public class AccountManagement : BusinessObject {

        public AccountManagement() : base() { }
        public AccountManagement(ISession session) : base(session) { }

        public void RegisterUser(User newUser) {
            var userRepo = new UserRepository(_context);

            newUser.IdUserType = UserType.User;
            newUser.UserDetail.ReferralId = GenerateReferralId();
            newUser.UserDetail.LastLoginDate = DateTime.Now;
            userRepo.Add(newUser);

            SaveChanges();
        }

        public User GetUser(int id) {
            var userRepo = new UserRepository(_context);

            return userRepo.FindByKey(id);
        }

        public User GetUser(string referralId) {
            var userRepo = new UserRepository(_context);

            return userRepo.FindByReferralId(referralId);
        }

        public User FindUserByEmail(string email) {
            var userRepo = new UserRepository(_context);

            return userRepo.FindByEmail(email);
        }

        string GenerateReferralId() {
            const string chars = "0123456789abcdefghijklmnopqrstuvwxyz";
            const int maxchars = 6;
            var retVal = new StringBuilder();
            var rnd = new Random();
            var userRepo = new UserRepository(_context);
            var referralIdList = userRepo.GetAllReferralId();

            do {
                retVal.Clear();
                for (int i = 0; i < maxchars; i++) {
                    retVal.Append(chars[rnd.Next(chars.Length)]);
                }
            } while (referralIdList.Contains(retVal.ToString()));

            return retVal.ToString();
        }
    }
}
